﻿using DependencyInjectionHelperLib.Extensions;
using DependencyInjectionHelperLib.Navigation;
using Microsoft.Extensions.DependencyInjection;

namespace DependencyInjectionHelperLib
{
    /// <summary>
    /// 依赖注入容器类，用于管理服务的注册和解析。
    /// </summary>
    public sealed class DIContainer
    {
        private static readonly Lazy<DIContainer> _DIContainer = new Lazy<DIContainer>(() => new DIContainer());

        public static DIContainer Default => _DIContainer.Value;

        private IServiceCollection _servicesCollection;
        private IServiceProvider? _serviceProvider;

        private DIContainer()
        {
            _servicesCollection = new ServiceCollection();
            _servicesCollection
                .AddSingleton<INavigationObjectProvider>(serviceProvider => new NavigationObjectProvider(_servicesCollection, serviceProvider))
                .AutoRegisterServices();
        }

        /// <summary>
        /// 注册服务并构建服务提供者，所有的服务只能在同一处进行注册。
        /// </summary>
        /// <param name="Register">可选的委托，用于注册额外的服务。</param>
        public void RegisterAndBuildServices(Action<IServiceCollection>? Register = null)
        {
            Register?.Invoke(_servicesCollection);
            if (_serviceProvider == null)
            {
                _serviceProvider = _servicesCollection.BuildServiceProvider();
            }
        }

        /// <summary>
        /// 获取服务提供者实例。
        /// </summary>
        /// <returns>服务提供者实例。</returns>
        /// <exception cref="InvalidOperationException">如果服务提供者尚未构建，则引发此异常。</exception>
        public IServiceProvider GetServiceProvider()
        {
            if (_serviceProvider == null)
            {
                throw new InvalidOperationException("Service provider has not been built yet. Call BuildServiceProvider first.");
            }
            return _serviceProvider;
        }
    }
}